/*
 * @lc app=leetcode.cn id=583 lang=typescript
 *
 * [583] 两个字符串的删除操作
 */

// @lc code=start
function minDistance(word1: string, word2: string): number {
  const m = word1.length;
  const n = word2.length;
  // dp[i][j]表示word1中前i个字符和word2中前j个字符的最长公共子序列的长度
  const dp = new Array(m + 1).fill(0).map((_) => new Array(n + 1).fill(0));

  for (let i = 1; i <= m; i++) {
    const a = word1[i - 1];
    for (let j = 1; j <= n; j++) {
      const b = word2[j - 1];
      if (a === b) {
        dp[i][j] = dp[i - 1][j - 1] + 1;
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
      }
    }
  }

  // 最长公共子序列长度
  const lsc = dp[m][n];
  // 两个单词减去最长公共子序列长度就是答案
  return m - lsc + n - lsc;
}
// @lc code=end
